package com.rc.saas.tenant.controller.tenant;

import com.alibaba.fastjson.JSON;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.config.UpYunConfig;
import com.rc.saas.tenant.model.enterprise.EnterpriseMember;
import com.rc.saas.tenant.model.operator.TenantOperator;
import com.rc.saas.tenant.model.tenant.*;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberService;
import com.rc.saas.tenant.service.operator.TenantOperatorService;
import com.rc.saas.tenant.service.tenant.*;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.tenant.TenantRoleDataAuthVo;
import com.rc.saas.tenant.vo.tenant.TreeModel;
import com.rc.saas.tenant.vo.tenant.TreeNodeModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

import static java.lang.String.format;

/**
 * 首页功能
 */
@Controller
@RequestMapping("/")
public class IndexController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(IndexController.class);

    private final String CONSOLE_PAGE = "/console";

    @Autowired
    private UpYunConfig upYunConfig;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private TenantOperatorService tenantOperatorService;

    @Autowired
    private EnterpriseMemberService enterpriseMemberService;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private TenantNavService tenantNavService;

    @Autowired
    private TenantRoleMenuService tenantRoleMenuService;

    @Autowired
    private TenantRoleService tenantRoleService;

    /**
     * 登录后的主页
     * @param response
     * @return
     */
    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String welcome(HttpServletResponse response, Model model) {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
        response.addHeader("Access-Control-Allow-Methods", "POST");
        response.addHeader("Access-Control-Max-Age", "1000");

        TenantUser user = ShiroUtils.getSessionUser();
        logger.info("当前用户:{}", JSON.toJSONString(user));
        if (user == null) {
            return "/login";
        }

        model.addAttribute("user", user);

        //构建导航菜单(只显示没有隐藏的菜单)
        //List<TreeVo<MenuVo>> leftMenus = tenantNavService.listMenuTree(user);
        //model.addAttribute("leftMenus", leftMenus);

        //根据不同的用户类型生成不同的TOP菜单,用户类型 0 运营商 1 分销商 2企业帐户  默认0
        List<TreeNodeModel> topMenus = tenantNavService.listTopMenuTreeByUser(user);
        if(!CollectionUtils.isEmpty(topMenus)){
            for (TreeNodeModel nodeModel:topMenus) {
                List<TreeModel<TreeNodeModel>> childList = tenantNavService.listLeftMenuTreeByUser(user, nodeModel.getMenuId());
                if(!CollectionUtils.isEmpty(childList) && !Objects.isNull(childList.get(0)) && !CollectionUtils.isEmpty(childList.get(0).getChildren())){
                    nodeModel.setChildList(childList.get(0).getChildren());
                }
            }
        }
        model.addAttribute("topMenus", topMenus);
//
//        if (!"2".equals(user.getUserType())) {
//            //企业主会员不显示首页
//            //默认首页
//            model.addAttribute("showPage", CONSOLE_PAGE);
//        }



        Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());
        model.addAttribute("tenant", tenant);
        model.addAttribute("showPage", CONSOLE_PAGE);
        model.addAttribute("hasConsolePermission", 0);


        if (!"0".equals(user.getUserType())) {
            TenantRoleMenuExample example = new TenantRoleMenuExample();
            example.createCriteria().andTenantMenuIdEqualTo(446L).andTenantRoleIdEqualTo(user.getTenantRoleId());
            TenantRoleMenu roleMenu = tenantRoleMenuService.selectByExample(example).stream().findFirst().orElseGet(() -> null);
            if (roleMenu != null) {
                model.addAttribute("hasConsolePermission", 1);
            }

        } else {
            model.addAttribute("hasConsolePermission", 1);
        }



        return "/home";
    }


    /**
     * 登录后的主页
     * @param response
     * @param model
     * @param topMenuId
     * @return
     */
    @RequestMapping(value = "/welcome2/{topMenuId}", method = RequestMethod.GET)
    public String welcome2(HttpServletResponse response, Model model, @PathVariable("topMenuId") Long topMenuId) {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
        response.addHeader("Access-Control-Allow-Methods", "POST");
        response.addHeader("Access-Control-Max-Age", "1000");

        TenantUser user = ShiroUtils.getSessionUser();
        logger.info("当前用户:{}", JSON.toJSONString(user));
        if (user == null) {
            return "/login";
        }
        model.addAttribute("user", user);

        //根据不同的用户类型生成不同的TOP菜单,用户类型 0 运营商 1 分销商 2企业帐户  默认0
        List<TreeNodeModel> topMenus = tenantNavService.listTopMenuTreeByUser(user);
        model.addAttribute("topMenus", topMenus);
        model.addAttribute("topMenuId", topMenuId);

        //根据不同的用户类型生成不同的LEFT导航菜单(只显示没有隐藏的菜单)
        List<TreeModel<TreeNodeModel>> leftMenus = tenantNavService.listLeftMenuTreeByUser(user, topMenuId);
        model.addAttribute("leftMenus", leftMenus);

        //默认首页
        if (!CollectionUtils.isEmpty(leftMenus)) {
            TreeModel<TreeNodeModel> rootNode = leftMenus.get(0);
            if (!CollectionUtils.isEmpty(leftMenus) && rootNode.getChildren().size() > 0) {
                List<TreeModel<TreeNodeModel>> children = rootNode.getChildren();
                //自动打开首个子菜单
                TreeModel<TreeNodeModel> firstChildNode = children.get(0);
                model.addAttribute("showPage", firstChildNode.getAttributes().get("url"));
            }
        }
        Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());
        model.addAttribute("tenant", tenant);
        model.addAttribute("uploadPath", upYunConfig.getDownloadRoot());


        if (!"0".equals(user.getUserType())) {
            TenantRoleMenuExample example = new TenantRoleMenuExample();
            example.createCriteria().andTenantMenuIdEqualTo(446L).andTenantRoleIdEqualTo(user.getTenantRoleId());
            TenantRoleMenu roleMenu = tenantRoleMenuService.selectByExample(example).stream().findFirst().orElseGet(() -> null);
            if (roleMenu != null) {
                model.addAttribute("hasConsolePermission", 1);
            }

        } else {
            model.addAttribute("hasConsolePermission", 1);
        }
        return "/home";
    }

    /**
     * 控制台
     * @param response
     * @return
     */
    @RequestMapping(value = "/console", method = RequestMethod.GET)
    public String console(HttpServletResponse response, Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        if ("2".equals(user.getUserType())) {

        }
        TenantRole tenantRole = tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
        String dataAuth = tenantRole.getDataAuth();
//        String dataAuth = format("%03d", tenantRole.getDataAuth());
        model.addAttribute("dataAuth",tenantRole.getDataAuth());

        String isPlatformAuth = dataAuth.substring(0, 1);
        String isOperatorAuth = dataAuth.substring(1, 2);
        if ("1".equals(isPlatformAuth) && "1".equals(isOperatorAuth)) {
            model.addAttribute("isBizTypebutton","0");
        }else {
            model.addAttribute("isBizTypebutton","1");
        }

        logger.info("打开控制台.......");
        return "/console";
    }

    /**
     * 基本信息
     * @param response
     * @return
     */
    @RequestMapping(value = "/basic", method = RequestMethod.GET)
    public String basic(HttpServletResponse response, Model model) {
        logger.info("打开基本信息.......");

        TenantUser user = getSessionTenantUser();

        user = tenantUserService.selectByLoginName(user.getLoginName());
        //处理手机号中间4位替换成*
        user.setMobile(user.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));

        //运营商
        Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());

        //分销商
        TenantOperator operator = tenantOperatorService.selectByLoginName(user.getLoginName());

        //企业帐户
        EnterpriseMember enterprise = enterpriseMemberService.selectByPrimaryKey(user.getEnterpriseId());

        model.addAttribute("uploadPath", upYunConfig.getDownloadRoot());
        model.addAttribute("user", user);
        model.addAttribute("tenant", tenant);
        model.addAttribute("operator", operator);
        model.addAttribute("enterprise", enterprise);
        return "/basic";
    }

    /**
     * 空白页面
     * @param response
     * @return
     */
    @RequestMapping(value = "/empty", method = RequestMethod.GET)
    public String empty(HttpServletResponse response, Model model) {
        return "/empty";
    }

}
